<template>
  <div class="search-wrap">
    <div class="search-head">
      <div class="search-box">
        <div class="search-con">
          <img src="./search.png" class="logo" onclick="return false"/>
          <input type="text" class="search" placeholder="请输入企业名称" v-model="keyword" maxlength="20"/>
          <img src="../../../assets/img/delete.png" class="clear" v-show="showIcon" @click="clearData"
               onclick="return false">
        </div>
        <div class="search-btn" @click="search">搜索</div>
      </div>
      <div class="title-box">{{title}}</div>
    </div>


    <div class="recommend-content-box" ref="wrapper" v-if="showData == 1">
      <div class="recommend-content-list">

        <div class="recommend-content-item" v-for="(item,index) in recommendList" :key="index"
             v-if="recommendList.length">
          <img :src="item.mechanismUrl" class="company-pic2" v-if="item.mechanismUrl"/>
          <span class="company-pic1" v-else></span>
          <div class="company-con-box">
            <span class="company-name">{{item.mechanismName}}</span>
            <span class="company-post">{{item.workTypeName}}</span>
          </div>
          <div class="recommend-pic-box" v-if="item.recommendType == 0" @click="recommendWork(item.id)">
            <img src="./message.png" class="company-pic3" onclick="return false"/>
          </div>
          <span class="recommend-text" v-if="item.recommendType == 1">已推荐</span>
        </div>

        <div class="recommend-more-box" v-if="noMoreData && showData == 1">没有更多了~</div>

      </div>
    </div>

    <div class="empty-wrap" v-if="showData == 2">
      <div class="empty-box">
        <div class="img-box"><img src="../empty.png" class="empty" onclick="return false"/></div>
        <div class="tip">搜索尚无结果，更多企业正在洽谈中，敬请期待！</div>
      </div>
    </div>


    <div class="content-box" v-if="showData == 0 && hisItem.length > 0">
      <div class="content-list">
        <div class="content" v-for="(item,index) in hisItem" :key="index" @click="queryResult(item)">{{item}}</div>
      </div>
      <div class="clear-box">
        <div class="clear-con" @click="clear">
          <img src="./clear.png" class="clear" onclick="return false"/>
          <span class="title">清空历史记录</span>
        </div>
      </div>
    </div>

  </div>
</template>

<script>
  import {baseUrl} from "../../../config/env";
  import {getDeviceRatio} from "../../../config/util";
  import BScroll from 'better-scroll';
  /*获取当前缩放比*/
  const DEVICE_RATIO = getDeviceRatio();
  /**
   *
   * @param threshold 触发事件的阀值，即滑动多少距离触发
   */
  /*上拉配置*/
  const UP_CONFIG = {
    threshold: -80 * DEVICE_RATIO,
  };

  export default {
    inject: ['reload'],
    data() {
      return {
        showData: 0,
        keyword: "",
        showIcon: false,
        hisTime: [],//搜索时间
        hisItem: [],//搜索内容,
        title: "历史搜索",
        recommendList: [],
        recommendScroll: null,
        currentPage: 1,
        PageSize: 20,
        noMoreData: false,
        userSign: "",
        userId: this.$route.query.userId,
        inviteType: this.$route.query.inviteType,
        affiliationId: this.$route.query.affiliationId
      }
    },
    created() {
      let base64 = require('js-base64').Base64;
      this.userSign = base64.decode(sessionStorage.getItem("success"));
      this.init();
    },
    methods: {
      queryRecommend() {
        this.$vux.loading.show({
          text: '加载中',
        });

        let time = (new Date()).getTime();
        let url = baseUrl + "/work/get_work_mechanism_list?timestamp=" + time;
        let param = {"sgin": this.userSign, "timestamp": time};
        let signature = this.$signature(url, param);

        this.axios.get(baseUrl + "/work/get_work_mechanism_list?sgin=" + this.userSign + "&userId=" + this.userId + "&mechanismName=" + this.keyword + "&mechanismAddress=" + "&page=" + this.currentPage + "&size=" + this.PageSize + "&auth=" + signature + "&timestamp=" + time).then((res) => {
          let resultObj = res.data;
          this.$vux.loading.hide();
          if (resultObj.code == 0 && resultObj.data != null) {
            if (resultObj.data.length > 0) {
              this.showData = 1;
              this.recommendList = resultObj.data;

              this.$nextTick(() => {
                this.initScroll();
                this.recommendScroll.on('touchEnd', (pos) => {
                  if (Math.abs(Math.round(pos.y)) > Math.abs(Math.round(this.recommendScroll.maxScrollY + 1))) {
                    this.loadMore();
                  }
                });
              });
            } else {
              this.showData = 2;
            }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.loading.hide();
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      search() {//搜索
        if (this.keyword == "" || this.keyword == undefined || this.keyword == null) {
          this.$vux.toast.text("请输入企业名称", "middle");
          return;
        }
        let key = (new Date()).getTime();
        let flag = this.findArray(this.keyword, this.hisItem);
        if (flag) {//输入的内容localStorage有记录
          for (let i = 0; i < localStorage.length; i++) {
            if (this.keyword == localStorage.getItem(localStorage.key(i))) {
              localStorage.removeItem(localStorage.key(i));
            }
          }
          localStorage.setItem(key, this.keyword);
        } else {
          if (this.hisItem.length >= 10) {
            localStorage.removeItem(this.hisTime[0]);
            localStorage.setItem(key, this.keyword);
          } else {
            localStorage.setItem(key, this.keyword)
          }
        }
        //初始化
        this.currentPage = 1;
        this.PageSize = 20;
        this.queryRecommend();
        this.init();
      },
      queryResult(name) {
        this.keyword = name;
        this.currentPage = 1;
        this.PageSize = 20;
        this.queryRecommend();
      },
      init() {//初始化
        this.hisTime = [];
        this.hisItem = [];
        for (let i = 0; i < localStorage.length; i++) {
          if (!isNaN(localStorage.key(i))) {
            this.hisItem.push(localStorage.getItem(localStorage.key(i)));
            this.hisTime.push(localStorage.key(i));
            this.showData = 0;
          }
        }
        this.hisItem = this.hisItem.reverse();
      },
      findArray(index, array) {
        for (let i = 0; i < array.length; i++) {
          if (array[i] === index) {
            return true;
          }
        }
      },
      clear() {//清除
        for (let i = 0; i < this.hisTime.length; i++) {
          localStorage.removeItem(this.hisTime[i]);
        }
        this.showData = 0;
        this.init();
      },
      clearData() {
        this.keyword = "";
        this.showIcon = false;
      },
      recommendWork(workId) {//推荐
        let time = (new Date()).getTime();
        let url = baseUrl + "/invite/send_mechanism?timestamp=" + time;
        let param = {"sgin": this.userSign, "timestamp": time};
        let signature = this.$signature(url, param);

        this.axios.get(baseUrl + "/invite/send_mechanism?sgin=" + this.userSign + "&id=" + this.affiliationId + "&type=" + this.inviteType + "&workId=" + workId + "&auth=" + signature + "&timestamp=" + time).then((res) => {
          let resultObj = res.data;
          if (resultObj.code == 0) {
            if (resultObj.data == 0) {
              this.$vux.toast.text("推荐失败，请重试", "middle");
            } else {
              this.currentPage = 1;
              this.PageSize = 20;
              this.queryRecommend();
            }
          } else {
            this.$vux.toast.text(resultObj.msg, "middle");
          }
        }).catch((error) => {
          this.$vux.toast.text("网络异常", "middle");
        });
      },
      loadMore() {//加载更多
        if (!this.noMoreData) {
          this.$vux.loading.show({
            text: '加载中',
          });
          let time = (new Date()).getTime();
          let url = baseUrl + "/work/get_work_mechanism_list?timestamp=" + time;
          let param = {"sgin": this.userSign, "timestamp": time};
          let signature = this.$signature(url, param);

          setTimeout(() => {
            this.axios.get(baseUrl + "/work/get_work_mechanism_list?sgin=" + this.userSign + "&userId=" + this.userId + "&mechanismName=" + this.keyword + "&page=" + (++this.currentPage) + "&size=" + this.PageSize + "&auth=" + signature + "&timestamp=" + time).then((res) => {
              let resultObj = res.data;
              if (resultObj.code == 0) {
                if (resultObj.data.length > 0) {
                  this.recommendList = this.recommendList.concat(resultObj.data);
                } else {
                  this.noMoreData = true;
                }
                this.$vux.loading.hide();
              } else {
                this.$vux.loading.hide();
                this.$vux.toast.text(resultObj.msg, "middle");
              }
            })
          }, 500)
        }
      },
      initScroll() {//初始化BScroll
        if (!this.recommendScroll) {
          this.recommendScroll = new BScroll(this.$refs.wrapper, {
            probeType: 3,
            deceleration: 0.003,
            bounce: false,
            swipeTime: 2000,
            click: true,
            pullUpLoad: UP_CONFIG
          });
        } else {
          this.recommendScroll.refresh();
        }
      },
      enable() {
        this.recommendScroll && this.recommendScroll.enable()
      },
      refresh() {
        this.recommendScroll && this.recommendScroll.refresh()
      },
      finishPullUp() {
        this.recommendScroll && this.recommendScroll.finishPullUp()
      }
    },
    watch: {
      keyword() {
        if (this.keyword == "" || this.keyword == undefined || this.keyword == null) {
          this.showIcon = false;
        } else {
          this.showIcon = true;
        }
        this.showData = 0;
      },
      recommendList() {
        this.$nextTick(() => {
          this.recommendScroll.refresh();
        })
      }
    },
    components: {
      BScroll
    }
  }
</script>

<style lang="stylus" scoped>
  @import "../../../assets/stylus/mixin.styl"

  .search-wrap
    wh(100%, auto)
    .search-head
      position: fixed
      top: 0
      wh(100%, auto)
      z-index: 99
      .search-box
        display: flex
        align-items: center
        wh(100%, 1.2rem)
        background: rgba(60, 175, 255, 1)
        .search-con
          display: flex
          margin-left: 0.32rem
          align-items: center
          flex: 1
          wh(8.213rem, 0.8rem)
          background: rgba(255, 255, 255, 1)
          border-radius: 0.387rem
          .logo
            margin-left: 0.2rem
            margin-right: 0.2rem
            wh(0.4rem, 0.4rem)
          .search
            wh(80%, 0.5rem)
            line-height: 0.5rem
            size-color(0.373rem, rgba(174, 174, 174, 1))
          .clear
            margin-left: auto
            margin-right: 0.2rem
            wh(0.507rem, 0.507rem)
        .search-btn
          margin-left: 0.307rem
          margin-right: 0.347rem
          wh(1.307rem, 0.8rem)
          line-height: 0.8rem
          size-color(0.427rem, rgba(255, 255, 255, 1))
          text-align: center
      .title-box
        display: flex
        align-items: center
        padding-left: 0.32rem
        wh(100%, 0.8rem)
        size-color(0.347rem, rgba(153, 153, 153, 1))
        background: #F2F2F2

    .recommend-content-box
      position: fixed
      top: 2rem
      wh(100%, auto)
      bottom: 0
      z-index: 88
      background: rgba(242, 242, 242, 1)
      .recommend-content-list
        display: flex
        flex-direction: column
        wh(100%, auto)
        .recommend-content-item
          display: flex
          wh(100%, 1.76rem)
          align-items: center
          background: rgba(255, 255, 255, 1)
          border-bottom: 0.027rem solid rgba(242, 242, 242, 1)
          .company-pic1
            margin-left: 0.32rem
            margin-right: 0.36rem
            wh(1.6rem, 1.2rem)
            border-radius: 0.16rem
            background: #f5f5f5
          .company-pic2
            margin-left: 0.32rem
            margin-right: 0.36rem
            wh(1.6rem, 1.2rem)
            border-radius: 0.16rem
          .company-con-box
            display: flex
            flex-direction: column
            .company-name
              width: 5.8rem
              ellipsis()
              size-color(0.4rem, #333)
              font-weight: 500
              padding-bottom: 0.2rem
            .company-post
              size-color(0.373rem, #3CAFFF)
          .recommend-pic-box
            margin-left: auto
            margin-right: 0.56rem
            .company-pic3
              wh(0.64rem, 0.64rem)
          .recommend-text
            margin-left: auto
            margin-right: 0.56rem
            size-color(0.373rem, rgba(204, 204, 204, 1))
        .recommend-more-box
          text-align: center
          margin-top: 0.64rem
          padding-bottom: 0.8rem
          size-color(0.373rem, rgba(153, 153, 153, 1))
    .empty-wrap
      fj(center, center)
      wh(100%, auto)
      position: fixed
      top: 2rem
      left: 0
      right: 0
      bottom: 0
      z-index: -1
      .empty-box
        width: 4.773rem
        height: auto
        .img-box
          width: 100%
          height: 4.773rem
          .empty
            width: 100%
            height: 100%
        .tip
          display: flex
          justify-content: center
          margin-top: 0.387rem
          font-size: 0.373rem
          color: rgba(68, 68, 68, 1)
    .content-box
      position: fixed
      top: 2rem
      padding-left: 0.32rem
      wh(100%, auto)
      overflow: hidden
      .content
        display: flex
        align-items: center
        wh(100%, 1.173rem)
        size-color(0.4rem, rgba(51, 51, 51, 1))
        border-bottom: 1px solid rgba(238, 238, 238, 1)
        &:last-child
          border: none
      .clear-box
        display: flex
        align-items: center
        wh(100%, 1.173rem)
        border-top: 1px solid rgba(238, 238, 238, 1)
        .clear-con
          display: flex
          align-items: center
          .clear
            padding-right: 0.2rem
            wh(0.32rem, 0.413rem)
          .title
            size-color(0.4rem, rgba(51, 51, 51, 1))

</style>
